<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'unitmanage:unitEnterpriseDominant:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%" 
    destroyOnClose={true}
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <BaiduMap :path="BaiduMapPath"  @overlaycomplete="handleOverlayComplete" @clearPath="handleClearPath"></BaiduMap>
    <Modal
      v-model:open="showContractDialog"
      title="提示"
      :showCancelButton="false"
      :showOkButton="false"
    >
      <p>请在3天内上传维保合同</p> <!-- 假设为3天，可根据实际情况修改 -->
      <Button type="primary" @click="goToContractManagement">前往上传</Button>
    </Modal>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsUnitmanageUnitEnterpriseDominantForm">
  import { ref, unref, computed,defineEmits,defineProps, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { UnitEnterpriseDominant,unitEnterpriseDominantListData,unitEnterpriseDominantSave, unitEnterpriseDominantForm } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { areaTreeData} from '/@/api/sys/area';
  import {Office, officeTreeData,officeListData} from '/@/api/sys/office';
  import {dictDataListData } from  '/@/api/sys/dictData';
  import BaiduMap from '/@/components/BMap';
  import { Modal, Button } from 'ant-design-vue'; // 引入Dialog和Button组件




  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('unitmanage.unitEnterpriseDominant');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<UnitEnterpriseDominant>({} as UnitEnterpriseDominant);
  const ctrlPermi=ref<string>('')
  const ctrlPermi1=ref<string>('')
  const op = ref<string>('');
  const path=ref<any>([])


  const showContractDialog = ref(false); // 控制提示框显示隐藏
  const BaiduMapPath = ref<any>([]); // 百度地图路径
  
  // const EnterpriseName=ref('');

  const EnterpriseParams = ref<Recordable>({
     name:''
    });
  const pliceParams = ref<Recordable>({
     name:'',
     dominantType:"police_station"
    });
  const firePathParams = ref<Recordable>({ 
    name:'',
    dominantType:"fire_management_unit"
  });

  const maintenanceParams = ref<Recordable>({ 
    name:'',
    dominantType:"maintenance"
  });
 
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('详情') : t('详情'),
  }));
//表单内容
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('所属行政区划'),
      field: 'county',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
          api: areaTreeData,        
          allowClear: true,
          // mode: 'multiple', // 多选
          // onChange: (name) => {
          //   record.value.county=name
          //   // record.value.countyName=name
          // },
          fieldNames:{
          label:'name',
          value:'id'
        },
        disabled:true,
      },
      
    },
    // {
    //   label: t('主体名称'),
    //   field: 'name',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
      
    // },
    {
      label: t('所属主体'),
      field: 'unitCode',
      fieldLabel:"name",
      component: 'Select', 
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
          disabled:true,
        };
      },
      required: true,
      
    },
    {
      label: t('直属消防管理单位'),
      field: 'firePathId',
      fieldLabel:"firePath",
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: firePathParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          filterOption: false,
          allowClear: true,
          immediate: true,
          onSearch: (value: string) => {
            firePathParams.value.name = value;
            console.log(firePathParams.value);
          },
          disabled:true,
        };
      },
      required: true
    },
    {
      label: t('警务室'),              //警务室
      field: 'policeId',
      fieldLabel:"policeName",
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: pliceParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            pliceParams.value.name = value;
            console.log(pliceParams.value);
          },
          disabled:true,
        };
      },
    },
    {
      label: t('维保企业'),            //维保企业
      field: 'maintenanceId',
      fieldLabel: 'maintenanceName',
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: maintenanceParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          filterOption: false,
          allowClear: true,
          immediate: true,
          onSearch: (value: string) => {
            maintenanceParams.value.name = value;
            console.log(maintenanceParams.value);
          },
          disabled:true,
        };
      },
    },
    {
      label: t('主体建筑类型'),
      field: 'monomer',
      component: 'RadioGroup',
      componentProps: {
        options:[
          { label: '建筑局部', value: '1' },
          { label: '多栋建筑', value: '2' },
        ],
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
    },
    {
      label: t('固定电话'),
      field: 'tel',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
    },
    {
      label: t('管理员姓名'),
      field: 'contacts',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
      required:true
    },
    {
      label: t('管理员电话'),
      field: 'mobile',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
      // required:true
    },
    {
      label: t('主体规模'),
      field: 'employeesNum',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
    },
    {
      label: t('详细地址'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
    },
    {
      label: t('联动消防力量'),
      field: 'unionEnterprise',
      fieldLabel:'remarks',
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
           mode:'multiple', // 多选
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
          disabled:true,
        };
      },
      required: true
    },
    {
      label: t('企业状态'),
      field: 'state',
      component: 'Select',
      componentProps: {
        maxlength: 100,
        options:[
          {label:'正常监控',value:'正常监控'},
          {label:'维保',value:'维保'},
          {label:'监督检查',value:'监督检查'},
          {label:'检测',value:'检测'},
        ],
        allowClear:true,
        disabled:true,
      },
    },  
     {
      label: t('主体类型'),
      field: 'dominantType',
      component: 'Select',
      componentProps: {
        maxlength: 100,
        dictType:'dominant_type',
        fieldNames:{
          label:'label',
          value:'value'
        },
        allowClear:true,
        disabled:true,
      },
    },
    {
      label: t('是否永久有效'),
      field: 'validForever',
      component: 'RadioGroup',
      componentProps: {
        maxlength: 100,
        options:[
          { label: '是', value: 'true' },
          { label: '否', value: 'false' },
        ],
        allowClear: true,
        disabled:true,
      },
    },
    {
      label: t('有效期'),
      field: 'expirationDate',
      component: 'DatePicker',
      componentProps: {
        maxlength: 100,
        allowClear: true,
        disabled:true,
      },
    },

    // {
    //   label: t('地图位置'),
    //   field: 'expirationDate',
    //   component: 'DatePicker',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    // },
   
  ];
//表单注册
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

//    watch(EnterpriseParams, (newParams) => {
//    const unitCodeSchema = inputFormSchemas.find(schema => schema.field === 'unitCode');
//    if (unitCodeSchema) {
//     unitCodeSchema.componentProps.params = newParams;
//     console.log('更新后的 unitCodeSchema.componentProps.params', unitCodeSchema.componentProps.params);
//         // 手动触发请求更新下拉框选项
//       if (registerForm.value) {
//         const selectComponent = registerForm.value.getComponentsRef('unitCode');
//         if (selectComponent && typeof selectComponent.fetchOptions === 'function') {
//           selectComponent.fetchOptions();
//         }
//       }
//   }
// }, { deep: true });




  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await unitEnterpriseDominantForm(data);
    BaiduMapPath.value = res.unitEnterpriseDominant.path ? JSON.parse(res.unitEnterpriseDominant.path) : [];
    record.value = (res.unitEnterpriseDominant || {}) as UnitEnterpriseDominant;
    record.value.__t = new Date().getTime();
      // 获取联动消防力量的id
      const unionEnterpriseId = record.value.unionEnterprise;
    if (unionEnterpriseId) {
      // 根据id查询对应的name
      const officeData = await officeTreeData();
      const findOffice = findItemById(officeData, unionEnterpriseId);
      if (findOffice) {
        record.value.enterpriseName = findOffice.name;
      }
    }
    if (record.value.path) {
    // record.value.path 是字符串形式的数组
    try {
      path.value = JSON.parse(record.value.path);
    } catch (error) {
      console.error('解析围栏数据失败:', error);
    }
  }
    setFieldsValue(record.value);
    // getFiledsValue(record.value);
    setDrawerProps({ loading: false });
  });

  // 处理 overlaycomplete 事件
const handleOverlayComplete = (newpath) => {
  path.value = newpath;
  console.log('Received fence data:', newpath);
};

const handleClearPath = () => {
  path.value = [];
  BaiduMapPath.value = [];
  console.log('Fence data cleared:', path.value);
};

  // 递归查找id对应的item
  function findItemById(data, id) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].id === id) {
        return data[i];
      }
      if (data[i].children && data[i].children.length > 0) {
        const result = findItemById(data[i].children, id);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }

  //异步提交请求
  async function handleSubmit() {
    try {
      //数据初始化
      let data = await validate();
      data = {
      ...data,
      path: JSON.stringify(path.value), // 使用 path 变量的值
      unitCode:data.unitCode,
      enterpriseName:data.enterpriseName,

    };
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      // console.log('submit', params, data, record);
      // console.log(params)
      console.log('data',data)
      const res = await unitEnterpriseDominantSave(params, data);
    //  console.log(res)
      showMessage(res.message);
      if (record.value.isNewRecord) {
        // 保存成功且为新增操作时显示提示框
        showContractDialog.value = true;
      }
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  const goToContractManagement = () => {
    router.push('/maintenance/management/inContract/list');
    showContractDialog.value = false; // 跳转后关闭提示框
 
  };

</script>
